package ta.structure;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class TADefinition
{
    private final TADeclaration globals;
    private HashMap<String, TATemplate> templates;
    //    private HashMap<String, TAElem> elemMap;
    private String name;

    public TADefinition()
    {
        globals = new TADeclaration();
        templates = new HashMap<>();
    }

    public String generateSystem()
    {
        StringBuilder res = new StringBuilder();
        ArrayList<String> list = new ArrayList<>();
        for (var template : templates.values())
        {
            if (template.isUnused())
                continue;
            res.append(String.format("%s_ins = %s(%s);\n", template.getName(), template
                    .getName(), generateParams(template)));
            list.add(template.getName() + "_ins");
        }
        res.append(String.format("system %s;", Arrays.stream(list.toArray())
                .reduce((x, y) -> String.format("%s, %s", x, y)).orElse("")));
        return res.toString();
    }

    public String generateParams(TATemplate t)
    {
        StringBuilder sb = new StringBuilder();
        if (t.getStartSignal() != null)
            sb.append(t.getStartSignal());
        if (t.getFinishSignal() != null)
        {
            sb.append(", ");
            sb.append(t.getFinishSignal());
        }
        return sb.toString();
    }

    public void addTemplate(TATemplate t)
    {
        templates.put(t.getName(), t);
    }

    public HashMap<String, TATemplate> getTemplates()
    {
        return templates;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public TADeclaration getGlobals()
    {
        return globals;
    }

//    public void addTAElem(TAElem elem)
//    {
//        this.elemMap.put(elem.) ;
//    }

//    public HashMap<String, TAElem> getElemMap()
//    {
//        return elemMap;
//    }
}
